# coding:utf-8

import hashlib
import uuid
import base64

__author__ = 'lee'


def cal_sha1_string(s):
    return str(hashlib.sha1(s.encode("utf-8")).hexdigest())


def cal_md5_file(file_path):
    fd = open(file_path, "rb")
    buffer = fd.read(8096)
    fd.close()
    return cal_md5_buffer(buffer)


def cal_md5_buffer(buffer):
    fmd5 = hashlib.md5(buffer)
    return fmd5.hexdigest()


def cal_md5_string(s):
    return str(hashlib.md5(s.encode("utf-8")).hexdigest())


def make_token():
    return str(uuid.uuid4()).replace("-", "")


def b64encode_string(string):
    if not isinstance(string, str):
        raise TypeError

    return base64.b64encode(string.encode()).decode()


def base64encode_uuid():
    uid = str(uuid.uuid4())
    return b64encode_string(uid)


def str_to_hex(s):
    return ' '.join([hex(ord(c)).replace('0x', '') for c in s])


def hex_to_str(s):
    return ''.join([chr(i) for i in [int(b, 16) for b in s.split(' ')]])


def str_to_bin(s):
    return ' '.join([bin(ord(c)).replace('0b', '') for c in s])


def bin_to_str(s):
    return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])
